package com.xxgc.vfc.auth.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.xxgc.vfc.api.dto.UserLoginDTO;
import com.xxgc.vfc.api.result.Result;
import com.xxgc.vfc.api.vo.PhoneAndPassLoginVO;
import com.xxgc.vfc.api.vo.UserPhoneRegisterVO;
import com.xxgc.vfc.auth.service.IUsersService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * @Author: SJY
 * @Date: 2023/11/10 15:13:52
 */
@Slf4j
@Api(tags = "登录注册")
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private IUsersService iUsersService;

    //注册方法
    @ApiOperation(value = "用户手机号注册")
    @PostMapping("/UserPhoneRegister")
    public Result UserPhoneRegister(@RequestBody @Valid UserPhoneRegisterVO userPhoneRegisterVO){
        iUsersService.userPhoneRegister(userPhoneRegisterVO);
        return Result.ok().msg("注册成功");
    }

    //登录
    @ApiOperation(value = "手机号密码登录")
    @PostMapping("/userPhoneAndPassLogin")
    public Result userPhoneAndPassLogin(
            @RequestBody @Valid PhoneAndPassLoginVO phoneAndPassLoginVO,
            HttpServletResponse response){
        UserLoginDTO userLoginDTO = iUsersService.userPhoneAndPassLogin(phoneAndPassLoginVO);
        //判断这个人是否已经登录
        String token = StpUtil.getTokenValueByLoginId(userLoginDTO.getId(), "web");
        //如果这个人web不为空
        if(!StrUtil.hasEmpty(token)){
            //进行强制下线
            // 指定`账号id`和`设备类型`进行强制注销
            StpUtil.logout(userLoginDTO.getId(), "web");
        }

        // 第1步，先登录上
        StpUtil.login(userLoginDTO.getId(),"web");
        // 第2步，获取 Token  相关参数
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        log.info("token是：{}",tokenInfo);
        response.setHeader("Authorization",tokenInfo.getTokenValue());

        // 返回当前token的登录设备类型
        String loginDevice = StpUtil.getLoginDevice();
        log.info("当前登录设备类型是{}",loginDevice);


        return Result.ok(userLoginDTO).msg("登录成功");
    }


}
